import 'package:flutter/material.dart';

class BackgroundPainter extends CustomPainter {
  final double gridLineWidth;
  final Color gridLineColor;

  final Color backgroundColor;

  final double horizontalSpacing;
  final double verticalSpacing;

  final Offset offset;
  final double scale;

  final bool showHorizontal;
  final bool showVertical;

  final double lineLength;

  final bool isAntialias;
  final bool matchParentSize;

  BackgroundPainter({
    this.gridLineWidth = 1.0,
    this.gridLineColor = Colors.black,
    this.backgroundColor = Colors.white,
    this.horizontalSpacing = 20,
    this.verticalSpacing = 20,
    this.offset = Offset.zero,
    this.scale = 1.0,
    this.showHorizontal = true,
    this.showVertical = true,
    this.lineLength = 1e4,
    this.isAntialias = true,
    this.matchParentSize = true,
  });

  @override
  void paint(Canvas canvas, Size size) {
    var lineHorizontalLength;
    var lineVerticalLength;
    if (matchParentSize) {
      lineHorizontalLength = size.width / scale;
      lineVerticalLength = size.height / scale;
    } else {
      lineHorizontalLength = lineLength / scale;
      lineVerticalLength = lineLength / scale;
    }

    var paint = Paint()
      ..style = PaintingStyle.stroke
      ..isAntiAlias = isAntialias
      ..color = gridLineColor
      ..strokeWidth = gridLineWidth;

    canvas.drawColor(backgroundColor,BlendMode.srcIn);

    if (showHorizontal) {
      var count = (lineVerticalLength / verticalSpacing).round();
      for (int i = -count + 1; i < count; i++) {
        canvas.drawLine(
          (Offset(-lineHorizontalLength, i * verticalSpacing) +
                  offset % verticalSpacing) *
              scale,
          (Offset(lineHorizontalLength, i * verticalSpacing) +
                  offset % verticalSpacing) *
              scale,
          paint,
        );
      }
    }

    if (showVertical) {
      var count = (lineHorizontalLength / horizontalSpacing).round();
      for (int i = -count + 1; i < count; i++) {
        canvas.drawLine(
          (Offset(i * horizontalSpacing, -lineVerticalLength) +
                  offset % horizontalSpacing) *
              scale,
          (Offset(i * horizontalSpacing, lineHorizontalLength) +
                  offset % horizontalSpacing) *
              scale,
          paint,
        );
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
